package com.software.backend.center.controller;

import com.software.backend.center.service.PersonnelCenterService;
import com.software.backend.center.service.PersonnelCenterServiceImpl;
import okhttp3.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author 王俊坤
 * @version 1.0
 * @date 2023/4/18 10:51
 */

@Controller
@RequestMapping("/personnelCenter")
public class PersonnelCenterController {

    @Autowired
    Environment environment;

    @Autowired
    private PersonnelCenterService personnelCenterService;


    @GetMapping("/headPortrait/{userId}/{versionCode}")
    public void getHeadPortrait(@PathVariable String userId, @PathVariable String versionCode, HttpServletResponse response) throws IOException {
        /**
         * 图片存储位置：当前微服务所在服务器，无文件夹层级，按照userId来区分不同人的头像，暂时无法记录历史头像
         * 命名规范：<userId>head<头像历史号>.jpeg
         * 数据库存储：不存储访问路径（配置在项目中），只存储图片的<头像历史号>部分,<userId>部分通过UserId获得
         * 在上传head时会进行图片类型转换，标准化为jpeg防止恶意修改
         */
        String imagePath = environment.getProperty("imagePath") + userId + "head" + versionCode + ".jpeg";
        String headToSring = personnelCenterService.getPeresonnelHead(imagePath);
        byte[] headBytesDecoded = Base64.getDecoder().decode(headToSring);
        if (headToSring != null){
            response.setContentType("image/jpeg");
            response.getOutputStream().write(headBytesDecoded);
            response.flushBuffer();
        }else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
}
